<template>
  <view>
    <view class="uni-header">
      <view class="uni-group">
        <view class="uni-title"></view>
        <view class="uni-sub-title"></view>
      </view>
      <view class="uni-group">
        <input class="uni-search" type="text" v-model="query" @confirm="search" placeholder="请输入搜索内容" />
        <button class="uni-button" type="default" size="mini" @click="search">搜索</button>
        <button class="uni-button" type="default" size="mini" @click="navigateTo('./add')">新增</button>
        <button class="uni-button" type="warning" size="mini" @click="debugUserInfo">调试用户</button>
        <button class="uni-button" type="warning" size="mini" @click="debugTenants">调试商户</button>
        <button class="uni-button" type="danger" size="mini" @click="setForceAdmin">设为管理员</button>
        <button class="uni-button" type="default" size="mini" :disabled="!selectedIndexs.length" @click="delTable">批量删除</button>
        <download-excel class="hide-on-phone" :fields="exportExcel.fields" :data="exportExcelData" :type="exportExcel.type" :name="exportExcel.filename">
          <button class="uni-button" type="primary" size="mini">导出 Excel</button>
        </download-excel>
      </view>
    </view>
    <view class="uni-container">
      <unicloud-db ref="udb" :collection="collectionList" :field="field" :where="where" page-data="replace"
        :orderby="orderby" :getcount="true" :page-size="options.pageSize" :page-current="options.pageCurrent"
        v-slot:default="{data,pagination,loading,error,options}" :options="options" loadtime="manual" @load="onqueryload">
        <uni-table ref="table" :loading="loading" :emptyText="error.message || '没有更多数据'" border stripe type="selection" @selection-change="selectionChange">
          <uni-tr>
            <uni-th align="center" v-if="isAdmin" filter-type="search" @filter-change="filterChange($event, 'tenant_id')" sortable @sort-change="sortChange($event, 'tenant_id')">商户ID</uni-th>
            <uni-th align="center" v-if="isAdmin">商户名称</uni-th>
            <uni-th align="center" filter-type="search" @filter-change="filterChange($event, 'name')" sortable @sort-change="sortChange($event, 'name')">分类名称</uni-th>
            <uni-th align="center" filter-type="range" @filter-change="filterChange($event, 'sort')" sortable @sort-change="sortChange($event, 'sort')">排序值</uni-th>
            <uni-th align="center" filter-type="select" :filter-data="options.filterData.status_localdata" @filter-change="filterChange($event, 'status')">状态</uni-th>
            <uni-th align="center" filter-type="timestamp" @filter-change="filterChange($event, 'created_at')" sortable @sort-change="sortChange($event, 'created_at')">创建时间</uni-th>
            <uni-th align="center" filter-type="timestamp" @filter-change="filterChange($event, 'updated_at')" sortable @sort-change="sortChange($event, 'updated_at')">更新时间</uni-th>
            <uni-th align="center">操作</uni-th>
          </uni-tr>
          <uni-tr v-for="(item,index) in data" :key="index">
            <uni-td align="center" v-if="isAdmin">{{item.tenant_id}}</uni-td>
            <uni-td align="center" v-if="isAdmin">{{getTenantName(item.tenant_id) || '平台分类'}}</uni-td>
            <uni-td align="center">{{item.name}}</uni-td>
            <uni-td align="center">{{item.sort}}</uni-td>
            <uni-td align="center">{{options.status_valuetotext[item.status]}}</uni-td>
            <uni-td align="center">
              <uni-dateformat :threshold="[0, 0]" :date="item.created_at"></uni-dateformat>
            </uni-td>
            <uni-td align="center">
              <uni-dateformat :threshold="[0, 0]" :date="item.updated_at"></uni-dateformat>
            </uni-td>
            <uni-td align="center">
              <view class="uni-group">
                <button @click="navigateTo('./edit?id='+item._id, false)" class="uni-button" size="mini" type="primary" :disabled="!isAdmin && item.tenant_id !== currentTenantId">修改</button>
                <button @click="confirmDelete(item._id)" class="uni-button" size="mini" type="warn" :disabled="!isAdmin && item.tenant_id !== currentTenantId">删除</button>
              </view>
            </uni-td>
          </uni-tr>
        </uni-table>
        <view class="uni-pagination-box">
          <uni-pagination show-icon :page-size="pagination.size" v-model="pagination.current" :total="pagination.count" @change="onPageChanged" />
        </view>
      </unicloud-db>
    </view>
  </view>
</template>

<script>
  import { enumConverter, filterToWhere } from '../../js_sdk/validator/food_categories.js';

  const db = uniCloud.database()
  // 表查询配置
  const dbOrderBy = '' // 排序字段
  const dbSearchFields = [] // 模糊搜索字段，支持模糊搜索的字段列表。联表查询格式: 主表字段名.副表字段名，例如用户表关联角色表 role.role_name
  // 分页配置
  const pageSize = 20
  const pageCurrent = 1

  const orderByMapping = {
    "ascending": "asc",
    "descending": "desc"
  }

  export default {
    data() {
      return {
        collectionList: "food_categories",
        field: "tenant_id,name,sort,status,created_at,updated_at",
        query: '',
        where: '',
        orderby: dbOrderBy,
        orderByFieldName: "",
        selectedIndexs: [],
        options: {
          pageSize,
          pageCurrent,
          filterData: {
            "status_localdata": [
              {
                "text": "禁用",
                "value": 0
              },
              {
                "text": "启用",
                "value": 1
              }
            ]
          },
          "status_valuetotext": {
            "0": "禁用",
            "1": "启用"
          }
        },
        imageStyles: {
          width: 64,
          height: 64
        },
        exportExcel: {
          "filename": "food_categories.xls",
          "type": "xls",
          "fields": {
            "商户ID": "tenant_id",
            "分类名称": "name",
            "排序值": "sort",
            "状态": "status",
            "创建时间": "created_at",
            "更新时间": "updated_at"
          }
        },
        exportExcelData: [],
        isAdmin: false,
        currentTenantId: '',
        tenantsMap: {} // 用于存储商户ID到商户名称的映射
      }
    },
    computed: {
      queryWhere() {
        if (!this.isAdmin && this.currentTenantId) {
          return {
            tenant_id: this.currentTenantId
          }
        }
        return {}
      }
    },
    onLoad() {
      this._filter = {}
      
      // 优先从 Vuex 获取用户信息（更可靠）
      // const userState = this.$store.state.user
      // 使用 uni-id-pages 提供的方法获取用户信息
      const userInfo = uni.getStorageSync('uni-id-pages-userInfo') || {}
      if (userInfo) {
        console.log('从Storage获取用户信息:', userInfo)
        this.isAdmin = userInfo.isAdmin
        this.currentTenantId = userInfo.tenant_id || ''
        
        // 设置初始查询条件
        this.where = this.queryWhere
      }
      
      this.getUserInfo()
      this.loadTenants()
    },
    onReady() {
      this.$refs.udb.loadData()
    },
    methods: {
      async getUserInfo() {
        try {
          const token = uni.getStorageSync('uni_id_token')
          if (!token) return
          
          // 不依赖Vuex，直接从Storage获取用户信息
          const userInfo = uni.getStorageSync('uni-id-pages-userInfo') || {}
          console.log('Storage用户信息:', userInfo)
          
          // 设置当前用户权限
          this.isAdmin = userInfo.isAdmin === true
          this.currentTenantId = userInfo.tenant_id || ''
          
          console.log('设置权限信息:', {
            isAdmin: this.isAdmin,
            tenant_id: this.currentTenantId
          })
          
          this.where = this.queryWhere
        } catch (e) {
          console.error('获取用户信息失败', e)
        }
      },
      async loadTenants() {
        try {
          console.log('开始加载商户数据')
          // 修复商户数据获取
          const { result } = await uniCloud.callFunction({
            name: 'get-tenants',
            data: {}
          })
          
          console.log('获取到的商户数据:', result)
          
          if (!result || !result.data) {
            console.error('未获取到商户数据')
            return
          }
          
          const data = result.data
          if (data) {
            this.tenantsMap = {}
            data.forEach(tenant => {
              // 尝试所有可能的字段名
              this.tenantsMap[tenant.tenant_id] = tenant.tenant_name || tenant.name || '未命名商户'
            })
            console.log('已加载商户数据:', this.tenantsMap)
          }
        } catch (e) {
          console.error('加载商户数据失败', e)
          // 提供错误详情
          console.error('错误详情:', e.message, e.stack)
        }
      },
      getTenantName(tenantId) {
        if (!tenantId) return '平台分类'
        // 调试时，显示更多信息
        console.log('getTenantName 被调用:', tenantId, '映射表:', this.tenantsMap)
        
        // 尝试从映射表获取名称
        const name = this.tenantsMap[tenantId]
        if (name) return name
        
        // 在页面加载时手动添加映射
        for (const key in this.tenantsMap) {
            console.log(`商户ID比较: [${key}] 与 [${tenantId}]`);
        }
        
        // 退化为显示ID
        return `商户(${tenantId})`
      },
      onqueryload(data) {
        this.exportExcelData = data
      },
      getWhere() {
        const query = this.query.trim()
        if (!query) {
          return ''
        }
        const queryRe = new RegExp(query, 'i')
        return dbSearchFields.map(name => queryRe + '.test(' + name + ')').join(' || ')
      },
      search() {
        let searchWhere = this.getWhere()
        let baseWhere = this.queryWhere
        
        let newWhere = ''
        if (searchWhere && Object.keys(baseWhere).length) {
          newWhere = {
            $and: [
              baseWhere,
              { $or: [{ name: new RegExp(this.query.trim(), 'i') }] }
            ]
          }
        } else if (searchWhere) {
          newWhere = { name: new RegExp(this.query.trim(), 'i') }
        } else {
          newWhere = baseWhere
        }
        
        this.where = newWhere
        this.$nextTick(() => {
          this.loadData()
        })
      },
      loadData(clear = true) {
        this.$refs.udb.loadData({
          clear
        })
      },
      onPageChanged(e) {
        this.selectedIndexs.length = 0
        this.$refs.table.clearSelection()
        this.$refs.udb.loadData({
          current: e.current
        })
      },
      navigateTo(url, clear) {
        uni.navigateTo({
          url,
          events: {
            refreshData: () => {
              this.loadData(clear)
            }
          }
        })
      },
      selectedItems() {
        var dataList = this.$refs.udb.dataList
        return this.selectedIndexs.map(i => dataList[i]._id)
      },
      delTable() {
        if (!this.isAdmin) {
          const dataList = this.$refs.udb.dataList
          const hasNoPermission = this.selectedIndexs.some(i => 
            dataList[i].tenant_id !== this.currentTenantId
          )
          
          if (hasNoPermission) {
            uni.showModal({
              title: '操作失败',
              content: '您没有权限删除其他商户的分类',
              showCancel: false
            })
            return
          }
        }
        
        this.$refs.udb.remove(this.selectedItems(), {
          success:(res) => {
            this.$refs.table.clearSelection()
          }
        })
      },
      selectionChange(e) {
        this.selectedIndexs = e.detail.index
      },
      confirmDelete(id) {
        if (!this.isAdmin) {
          const item = this.$refs.udb.dataList.find(item => item._id === id)
          if (item && item.tenant_id !== this.currentTenantId) {
            uni.showModal({
              title: '操作失败',
              content: '您没有权限删除其他商户的分类',
              showCancel: false
            })
            return
          }
        }
        
        this.$refs.udb.remove(id, {
          success:(res) => {
            this.$refs.table.clearSelection()
          }
        })
      },
      sortChange(e, name) {
        this.orderByFieldName = name;
        if (e.order) {
          this.orderby = name + ' ' + orderByMapping[e.order]
        } else {
          this.orderby = ''
        }
        this.$refs.table.clearSelection()
        this.$nextTick(() => {
          this.$refs.udb.loadData()
        })
      },
      filterChange(e, name) {
        this._filter[name] = {
          type: e.filterType,
          value: e.filter
        }
        let newWhere = filterToWhere(this._filter, db.command)
        
        if (!this.isAdmin && this.currentTenantId) {
          if (Object.keys(newWhere).length) {
            newWhere = {
              ...newWhere,
              tenant_id: this.currentTenantId
            }
          } else {
            newWhere = { tenant_id: this.currentTenantId }
          }
        }
        
        if (Object.keys(newWhere).length) {
          this.where = newWhere
        } else {
          this.where = this.queryWhere
        }
        this.$nextTick(() => {
          this.$refs.udb.loadData()
        })
      },
      debugUserInfo() {
        console.log('当前isAdmin状态:', this.isAdmin)
        console.log('当前tenant_id:', this.currentTenantId)
        console.log('Vuex用户状态:', this.$store.state.user)
        
        uni.showModal({
          title: '用户信息调试',
          content: `isAdmin: ${this.isAdmin}\ntenant_id: ${this.currentTenantId}`,
          showCancel: false
        })
      },
      debugTenants() {
        console.log('商户映射表:', this.tenantsMap)
        this.loadTenants() // 重新加载商户数据
        
        uni.showModal({
          title: '商户数据调试',
          content: '请查看控制台输出',
          showCancel: false
        })
      },
      setForceAdmin() {
        // 直接在本地设置
        this.isAdmin = true;
        
        // 同时尝试更新存储中的信息
        const userInfo = uni.getStorageSync('uni-id-pages-userInfo') || {}
        userInfo.isAdmin = true
        uni.setStorageSync('uni-id-pages-userInfo', userInfo)
        
        uni.showToast({
          title: '已设置为管理员',
          icon: 'success'
        });
        
        // 刷新当前页面
        this.$nextTick(() => {
          this.$refs.udb.loadData();
        });
      }
    }
  }
</script>

<style>
  .uni-button[disabled] {
    opacity: 0.5;
    cursor: not-allowed;
  }
  
  .system-tag {
    background-color: #e1f3d8;
    color: #67c23a;
    padding: 2px 6px;
    border-radius: 4px;
    font-size: 12px;
  }
</style>
